package com.mm.cloud.sys.auth.core.provider;

import com.mm.cloud.common.core.constant.SecurityConstants;
import com.mm.cloud.common.core.exception.BaseException;
import com.mm.cloud.common.security.helper.LoginUserHelper;
import com.mm.cloud.common.security.loginuser.LoginUser;
import com.mm.cloud.feign.sys.api.dto.BtnPermissionCodeFeignDTO;
import com.mm.cloud.feign.sys.api.service.IPermissionFeignService;
import com.mm.cloud.feign.sys.api.service.IUserFeignService;
import com.mm.cloud.feign.sys.api.vo.LoginUserVO;
import com.mm.cloud.sys.auth.core.provider.base.AuthenticationProvider;
import com.mm.cloud.sys.auth.core.token.UsernamePasswordAuthenticateToken;
import com.mm.cloud.sys.auth.core.token.base.AuthenticateToken;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.util.HashSet;
import java.util.List;

/**
 * 用户名密码身份验证提供者
 *
 * @author mr
 * @since 2021-07-10
 */
@AllArgsConstructor
@Component
public class UsernamePasswordAuthenticationProvider implements AuthenticationProvider {

    private final IUserFeignService userFeignService;

    private final IPermissionFeignService permissionFeignService;

    @Override
    public Object authenticate(AuthenticateToken authenticateToken) {
        UsernamePasswordAuthenticateToken usernamePasswordAuthenticateToken = (UsernamePasswordAuthenticateToken) authenticateToken;
        LoginUserVO loginUserVO = userFeignService.getUserByUsername(usernamePasswordAuthenticateToken.getUsername(), SecurityConstants.INNER).getData();
        if (ObjectUtils.isEmpty(loginUserVO)) {
            throw new BaseException("用户名或密码错误");
        }
        if (!LoginUserHelper.matchesPassword(usernamePasswordAuthenticateToken.getPassword(), loginUserVO.getPassword())) {
            throw new BaseException("用户名或密码错误");
        }

        BtnPermissionCodeFeignDTO dto = new BtnPermissionCodeFeignDTO();
        dto.setUserId(loginUserVO.getId());
        dto.setRoles(loginUserVO.getRoles());
        dto.setCompanyId(loginUserVO.getCompanyId());
        List<String> authorities = permissionFeignService.getBtnPermissionCode(dto, SecurityConstants.INNER).getData();
        return LoginUser
                .builder()
                .userId(loginUserVO.getId())
                .username(loginUserVO.getUsername())
                .companyId(loginUserVO.getCompanyId())
                .storeId(loginUserVO.getStoreId())
                .roles(loginUserVO.getRoles())
                .authorities(new HashSet<>(authorities))
                .token(LoginUserHelper.createToken())
                .build();
    }

    @Override
    public boolean supports(Class<?> var1) {
        return UsernamePasswordAuthenticateToken.class.isAssignableFrom(var1);
    }
}
